/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin;

import Utils.Static;
import Utils.Utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.POST;
import models.CategoryModel;
import models.ProductModel;
import org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID;

/**
 *
 * @author user
 */
public class products extends HttpServlet {

    boolean isPost = false;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            //check if is logged in
            HttpSession session = request.getSession(true);
            //check if is connect
            if (session.getAttribute(Static.adminID) == null) {
                getServletContext().getRequestDispatcher("/admin/login/index.jsp").forward(request, response);
            }

            String action = request.getParameter(Static.action);

            if (action == null) {
                List(request, response);
            } else if (action.compareTo("add") == 0) {
                Add(request, response);
            } else if (action.compareTo("delete") == 0) {
                Delete(request, response);
            } else if (action.compareTo("edit") == 0) {
                Edit(request, response);
            } else {
                List(request, response);
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        isPost = false;
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        isPost = true;
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void Add(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            CategoryModel categoryModel = new CategoryModel();
            ArrayList categories = categoryModel.GetSubCategories(-1);
            session.setAttribute(Static.categories, categories);

            if (!isPost) {
                getServletContext().getRequestDispatcher("/admin/products/add.jsp").forward(request, response);
                return;
            }

            String name = request.getParameter("name");
            String description = request.getParameter("description");
            double price = Double.parseDouble(request.getParameter("price"));
            int categoryID = Integer.parseInt(request.getParameter("categories"));
            double quantity = Double.parseDouble(request.getParameter("quantity"));


            if (name.compareTo("") == 0 || price == 0) {
                session.setAttribute(Static.error, "Numele si pretul obligatorii.");
                getServletContext().getRequestDispatcher("/admin/products/edit.jsp").forward(request, response);
                return;
            }

            ProductModel productModel = new ProductModel();
            if (productModel.AddProduct(name, description, price, categoryID, quantity) == -1) {
                session.setAttribute(Static.error, "Produsul nu a fost adaugat.");
            } else {
                session.setAttribute(Static.confirm, "Produsul a fost adaugat cu succes.");
            }

            response.sendRedirect("products");

        } catch (Exception ex) {
        }
    }

    public void Edit(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);

            int productID = Integer.parseInt(request.getParameter(Static.id));

            CategoryModel categoryModel = new CategoryModel();
            ArrayList categories = categoryModel.GetSubCategories(-1);
            session.setAttribute(Static.categories, categories);
            ProductModel productModel = new ProductModel();

            if (!isPost) {
                HashMap product = productModel.GetProduct(productID);
                session.setAttribute(Static.product, product);
                getServletContext().getRequestDispatcher("/admin/products/edit.jsp").forward(request, response);
                return;
            }

            //  Utils.UploadFile(request);

            
            String name = request.getParameter("name");
            String description = request.getParameter("description");
            double price = Double.parseDouble(request.getParameter("price"));
            int categoryID = Integer.parseInt(request.getParameter("categories"));
            double quantity = Double.parseDouble(request.getParameter("quantity"));


            if (name.compareTo("") == 0 || price == 0) {
                session.setAttribute(Static.error, "Numele si pretul obligatorii.");
                getServletContext().getRequestDispatcher("/admin/products/edit.jsp").forward(request, response);
                return;
            }

            if (productModel.UpdateProduct(productID, name, description, price, categoryID, quantity) == -1) {
                session.setAttribute(Static.error, "Produsul nu a fost actualizat.");
            } else {
                session.setAttribute(Static.confirm, "Produsul a fost actualizat cu succes.");
            }

            response.sendRedirect("products");

        } catch (Exception ex) {
            String error = ex.getMessage();
        }
    }

    public void Delete(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            int productID = Integer.parseInt(request.getParameter(Static.id));

            ProductModel productModel = new ProductModel();

            if (productModel.ActivateProduct(productID, 0) == -1) {
                session.setAttribute(Static.error, productModel.GetMessage());
            } else {
                session.setAttribute(Static.confirm, productModel.GetMessage());
            }
            response.sendRedirect("products");
        } catch (Exception ex) {
        }
    }

    public void Import() {
        try {
        } catch (Exception ex) {
        }
    }

    public void Export() {
        try {
        } catch (Exception ex) {
        }
    }

    public void List(HttpServletRequest request, HttpServletResponse response) {
        try {

            HttpSession session = request.getSession(true);
            String sortFields[][] = {{"Name", "Nume"}, {"Quantity", "Cantitate"}, {"Price", "Pret"}};
            String sort = sortFields[0][0];
            int pageSize = 10;
            int currPage = 1;
            int firstPage = 1;
            String sortDir = "asc";
            int categoryID = - 1;

            if (request.getParameter(Static.sort) != null) {
                sort = request.getParameter(Static.sort);
            }

            if (request.getParameter(Static.sortDir) != null) {
                sortDir = request.getParameter(Static.sortDir).compareTo("desc") == 0 ? "desc" : "asc";
            }

            if (request.getParameter(Static.currPage) != null) {
                currPage = Integer.parseInt(request.getParameter(Static.currPage));
            }

            if (request.getParameter(Static.firstPage) != null) {
                firstPage = Integer.parseInt(request.getParameter(Static.firstPage));
            }

            if (request.getParameter(Static.catID) != null) {
                categoryID = Integer.parseInt(request.getParameter(Static.catID));
            }

//calculez numarul de pagini
            ProductModel model = new ProductModel();
            int recordsCount = model.GetProducts_Count(-1);
            int pageCount = (int) (recordsCount / pageSize);

//extrag pagina currPage
            int offset = (currPage - 1) * pageSize;
            ArrayList products = model.GetProducts(offset, pageSize, sort, sortDir, categoryID);

//adaug variabilele in sesiune in sesiune

            session.setAttribute(Static.currPage, currPage);
            session.setAttribute(Static.firstPage, firstPage);
            session.setAttribute(Static.pageCount, pageCount);
            session.setAttribute(Static.sort, sort);
            session.setAttribute(Static.sortDir, sortDir);
            session.setAttribute(Static.sortFields, sortFields);
            session.setAttribute(Static.products, products);

            getServletContext().getRequestDispatcher("/admin/products/index.jsp").forward(request, response);

        } catch (Exception ex) {
        }
    }
}
